#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <assert.h>
#include <stdlib.h>

int main()
{
    //printf("This is parent: pid :%d\n",getpid());
    pid_t ret=fork();
    assert(ret!=-1);
    int num =5;
    if(ret==0){
        //child 
        while(num--){
            printf("child running:pid:%d,ppid:%d\n",getpid(),getppid());
            sleep(3);
            }
        exit(1);
    }
    
    //阻塞等待：父进程阻塞在此直至子进程完成并回收子进程再进行打印操作
    //waitpid(ret,NULL,0);
    // printf("child is over\n");


    //非阻塞等待
    int status=0;
    while(1){
        int childstate=waitpid(ret,&status,WNOHANG);  //使用WNOHANG时代表进行非阻塞等待，子进程是否完成不影响父进程的进行
        if(childstate==0){
            //进行非阻塞等待waitpid返回0时代表：waitpid调用成功&&子进程未退出
            printf("child still running\n");
        }
        else if(childstate>0){
            //返回值是子进程的pid时代表：waitpid调用成功&&子进程已退出
            printf("child is over\n");
            break;
        }
        else if(childstate==-1){
            //返回-1代表:waitpid调用失败
            printf("waitpid failed\n");
            break;
        }
        sleep(1);
    }
}

